<?php
/**
 * Step 1: Require the Slim PHP 5 Framework
 *
 * If using the default file layout, the `Slim/` directory
 * will already be on your include path. If you move the `Slim/`
 * directory elsewhere, ensure that it is added to your include path
 * or update this file path as needed.
 */
require 'Slim/Slim.php';

/**
 * Step 2: Instantiate the Slim application
 *
 * Here we instantiate the Slim application with its default settings.
 * However, we could also pass a key-value array of settings.
 * Refer to the online documentation for available settings.
 */
$app = new Slim();



/**
 * Introduce database connection
 */
require_once 'idiorm.php';
ORM::configure('mysql:host=mysql125.cp.united-hoster.de;dbname=db1015764_manno');
ORM::configure('username','u1015764_manno');
ORM::configure('password','oelbronn2012');






/**
 * Step 3: Define the Slim application routes
 *
 * Here we define several Slim application routes that respond
 * to appropriate HTTP request methods. In this example, the second
 * argument for `Slim::get`, `Slim::post`, `Slim::put`, and `Slim::delete`
 * is an anonymous function. If you are using PHP < 5.3, the
 * second argument should be any variable that returns `true` for
 * `is_callable()`. An example GET route for PHP < 5.3 is:
 */
//GET Default page
$app->get('/', function () {
	$template = <<<EOT
<!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8"/>
            <title>MannO WebService</title>
			<link rel="stylesheet" type="text/css" href="css/MannO.css">           
        </head>

        <body> 
 	<div class="site-wrapper">
		<header>
			<a class="site-logo" href="/"><img src="images/logo.png" style="width:120%;" alt="MannO WebService Logo"/></a>
		</header> 
		<article class="content">        
            <h1>Welcome to MannO WebService!</h1>
            <p>
                This is a RESTFUL WebService using GET and POST
            </p>
        	<section>
                <h2>How To retrieve data?</h2>
                <ol>
                    <li><a href="webservice.php/status">Most recent time in all tables</a></li>
                    <li>Blaaaa.....</li>                    
                </ol>
            </section>
            <section>
                <h2>How To Upload data?</h2>                
            </section>
            <section style="padding-bottom: 20px">
                <h2>ToDo List</h2>
                <ol>
                    <li><a href='/MannO/dbScheme.sql'>Setup Database Scheme</a></li>
                </ol>
            </section>
	</article>
	<footer class="site-footer">
    	<p>Developped by...</p>   
    </footer>
	</div>
        </body>
    </html>
EOT;
	echo $template;
});


//GET actual timestamps of all tables

$app->get('/status',function() {	
	echo "<?xml version='1.0' encoding='ISO-8859-15'?>\n";
	echo "<status>\n";

$status = ORM::for_table('club')
				->order_by_desc('timestamp')
				->find_one();
	echo "\t<club>".$status->timestamp."</club>\n";

$status = ORM::for_table('event')
				->order_by_desc('timestamp')
				->find_one();
	echo "\t<event>".$status->timestamp."</event>\n";

$status = ORM::for_table('match')
				->order_by_desc('timestamp')
				->find_one();
	echo "\t<match>".$status->timestamp."</match>\n";

$status = ORM::for_table('player')
				->order_by_desc('timestamp')
				->find_one();
	echo "\t<player>".$status->timestamp."</player>\n";

$status = ORM::for_table('playsFor')
				->order_by_desc('timestamp')
				->find_one();
	echo "\t<playsFor>".$status->timestamp."</playsFor>\n";
	echo "</status>";
});


//GET list of all clubs

$app->get('/clubs',function() {
	$clubs = 	ORM::for_table('club')
	->find_many();
	foreach ($clubs as $club) {
		echo '<a href="/MannO/webservice.php/players/'.$club->id.'">'.$club->name.'</a><br>';
	}

});


$app->get('/clubs/:id',function($id) {
	$clubs = 	ORM::for_table('club')
				->where_gt('id',$id)
				->find_many();
	echo "<?xml version='1.0' encoding='ISO-8859-15'?>\n<clubs>\n\t<list>\n";
	foreach ($clubs as $club) {
		echo "\t\t<club name='".$club->name."' id='".$club->id."' timestamp='".$club->timestamp."'/>\n";
	}
	echo "\t</list>\n</clubs>";
});

//GET club by id
$app->get('/club/:id',function($id) {
	$club = 	ORM::for_table('club')
				->where('id', $id)
				->find_one();

	echo '<a href="/MannO/webservice.php/players/'.$club->id.'">'.$club->name.'</a><br>';
});


$app->get('/players(/:clubID)',function($clubID = 0) {
$htmlhead = '<!DOCTYPE html>
    <html>
        <head>
            <title>MannO WebService</title>
			<link rel="stylesheet" type="text/css" href="/MannO/css/MannO.css">           
        </head><body><div class="site-wrapper">';
$htmlfoot = '</div></body></html>';
	$players = 	ORM::for_table('club')
				->table_alias('c')
				->join('playsFor', array('c.id' ,'=' ,'pf.clubID'),'pf')
				->join('player', array('p.id' ,'=' ,'pf.playerID'),'p')
				->select('c.name', 'clubName')
				->select('p.name', 'playerName');
				if($clubID != 0){
					$players=$players->where('c.id',$clubID);
				}
				$players=$players->order_by_asc('c.name')
				->order_by_asc('p.name')
				->find_many();
	echo $htmlhead . '<table><tr><th>Name</th><th>Club</th>';
	foreach($players as $p){
		echo '<tr><td>'. $p->playerName ."</td><td>".$p->clubName."</td><br>" ;
	}
	echo '</table>' . $htmlfoot;
});


$app->get('/matches',function() {
	echo "List of all matches<br>";
	$matches = ORM::for_table('match')
				->table_alias('m')
				->join('club', array('m.homeClubID', '=', 'home.id'),'home')
				->join('club', array('m.awayClubID', '=', 'away.id'),'away')
				->select('home.name', 'homeName')
				->select('away.name', 'awayName')
				->find_many();
	foreach($matches as $match){
		echo $match->homeName .' - '. $match->awayName;
	}
	
});


/*********************************************************************
* FUNKTIONALITY FOR ANDROID APP
*********************************************************************/
	/*****************************************************************
	* GET REQUESTS
	*****************************************************************/
//Get all clubs edited after timestamp
$app->get('/clubUpdate/:datetime',function($datetime) {
	$clubs = ORM::for_table('club')
				->where_gt('timestamp',$datetime)
				->find_many();
	echo "<?xml version='1.0' encoding='ISO-8859-15'?>\n<clubs>\n\t<list>\n";
	foreach ($clubs as $club) {
		echo "\t\t<club name='".$club->name."' id='".$club->id."' timestamp='".$club->timestamp."'/>\n";
	}
	echo "\t</list>\n</clubs>";
	
});

//Get all players edited after timestamp
$app->get('/playerUpdate/:datetime',function($datetime) {
	$players = ORM::for_table('player')
				->where_gt('timestamp',$datetime)
				->find_many();
	echo "<?xml version='1.0' encoding='ISO-8859-15'?>\n<players>\n\t<list>\n";
	foreach ($players as $player) {
		echo "\t\t<player name='".$player->name."' id='".$player->id."' timestamp='".$player->timestamp."'/>\n";
	}
	echo "\t</list>\n</players>";
	
});

//Get all matches edited after timestamp
$app->get('/matchUpdate/:datetime',function($datetime) {
	$matches = ORM::for_table('match')
				->where_gt('timestamp',$datetime)
				->find_many();
	echo "<?xml version='1.0' encoding='ISO-8859-15'?>\n<matches>\n\t<list>\n";
	foreach ($matches as $match) {
		echo "\t\t<match  id='".$match->id."' homeClubId='".$match->homeClubID."' awayClubId='".$match->awayClubID."' date='".$match->date."' timestamp='".$match->timestamp."'/>\n";
	}
	echo "\t</list>\n</matches>";
	
});

//Get all playsFor edited after timestamp
$app->get('/playsForUpdate/:datetime',function($datetime) {
	$playsFors = ORM::for_table('playsFor')
				->where_gt('timestamp',$datetime)
				->find_many();
	echo "<?xml version='1.0' encoding='ISO-8859-15'?>\n<playsFors>\n\t<list>\n";
	foreach ($playsFors as $playsFor) {
		echo "\t\t<playsFor  id='".$playsFor->id."' playerId='".$playsFor->playerID."' clubId='".$playsFor->clubID."'  start='".$playsFor->start."' end='".$playsFor->end."' timestamp='".$playsFor->timestamp."'/>\n";
	}
	echo "\t</list>\n</playsFors>";
	
});

//Get all events edited after timestamp
$app->get('/eventUpdate/:datetime',function($datetime) {
	$events = ORM::for_table('event')
				->where_gt('timestamp',$datetime)
				->find_many();
	echo "<?xml version='1.0' encoding='ISO-8859-15'?>\n<events>\n\t<list>\n";
	foreach ($events as $event) {
		
		echo "\t\t<event  id='".$event->id."' matchId='".$event->matchID."' type='".$event->type."' playsForId='".$event->playsForID."' playtime='".$event->playtime;
		if ($event->previousEventID != ""){
			echo "' previousEventId='".$event->previousEventID;
		}
		echo "' timestamp='".$event->timestamp."'>\n";
		if ($event->description != ""){
			echo "\t\t\t<description>".$event->description."</description>\n";
		}
		echo "\t\t</event>\n";
	}
	echo "\t</list>\n</events>";
});

	/*****************************************************************
	* POST REQUESTS
	*****************************************************************/
//POST route
$app->post('/post', function () {
	echo 'This is a POST route';
});






//PUT route
$app->put('/put/club/:id/:name', function ($id, $name) {
	$club = ORM::for_table('club')->find_one($id);
	if ($club == null){
		$club = ORM::for_table('club')->create();
	}
	$date =  date("Y-m-d H:i:s",time()+60*60);	
	$club->name = utf8_decode($name);
	$club->timestamp = $date;
	$club->save();
	echo "Club [".$club->id." (".$club->timestamp.")] ".$club->name;
});




//DELETE route
$app->delete('/delete', function () {
	echo 'This is a DELETE route';
});




/**
 * Step 4: Run the Slim application
 *
 * This method should be called last. This is responsible for executing
 * the Slim application using the settings and routes defined above.
 */
$app->run();

